package org.danysoft.encoding_converter.client;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

import org.danysoft.encoding_converter.core.CharsetRecognizer;
import org.danysoft.encoding_converter.core.ConvertHandler;
import org.danysoft.encoding_converter.core.exceptions.TooBigInputDataException;

public class Cli {

  public static void main(String[] args) {
    
    if (args.length < 3) {
      System.err.println("Too less arguments. ");
      System.err.println("Using: [inputFile] [outputFile] [charset]");
      return;
    }
    
    try {
    	
      String inFilePath = args[0];
      if (   inFilePath == null 
    	    || inFilePath.trim().length() == 0
      ) {
        System.err.println("wrong parameter argument [inputFile]=\"" + inFilePath + "\"");
        return;
      }
      String outFilePath = args[1];
      if (   outFilePath == null 
          || outFilePath.trim().length() == 0
      ) {
        System.err.println("wrong parameter argument [outputFile]=\"" + inFilePath + "\"");
        return;
      }
      String charsetString = args[2];
      if (   charsetString == null 
          || charsetString.trim().length() == 0
      ) {
        System.err.println("wrong parameter argument [charset]=\"" + charsetString + "\"");
        return;
      }
    	
      File inFile = new File(inFilePath);
      File outFile = new File(outFilePath);
      Charset charset = CharsetRecognizer.getCharsetByName(charsetString);
      
      if (!inFile.exists()) {
        System.err.println("Input file " + inFilePath + " doesn't exists.");
        return;
      }
      
      if (!inFile.canRead()) {
        System.err.println("Input file " + inFilePath + " isn't readable.");
        return;
      }
      
      if (!outFile.canWrite()) {
        System.err.println("Output file " + outFilePath + " isn't writeable.");
        return;
      }
      
      ConvertHandler.convert(inFile, outFile, charset);
      
    } catch (IOException e) {
      System.err.print(e.getLocalizedMessage());
    } catch (TooBigInputDataException e) {
      System.err.print(e.getLocalizedMessage());
    }
    
  }

}
